<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useCustomerServiceStore } from "@/store/modules/customerService";
import type { ClientUser } from "@/api/customer-service";

const store = useCustomerServiceStore();
const emit = defineEmits<{
  close: [];
}>();

const searchKeyword = ref("");
const onlineOnly = ref(false);

// 搜索用户
const handleSearch = () => {
  store.searchClientUsers(searchKeyword.value);
};

// 开始聊天
const startChat = async (user: ClientUser) => {
  await store.startChatWithUser(user.id);
  emit("close");
};

// 格式化时间
const formatTime = (dateStr?: string) => {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60));
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60));
      return minutes === 0 ? "刚刚" : `${minutes}分钟前`;
    }
    return `${hours}小时前`;
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 过滤在线用户
const filteredUsers = computed(() => {
  if (!onlineOnly.value) return store.clientUsers;
  return store.clientUsers.filter(u => u.online_status);
});

onMounted(() => {
  store.loadClientUsers({ per_page: 50 });
});
</script>

<template>
  <div class="user-list-panel">
    <div class="panel-header">
      <h3>用户列表</h3>
      <el-icon class="close-btn" @click="emit('close')"><Close /></el-icon>
    </div>

    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户名、手机号、邮箱"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-checkbox v-model="onlineOnly" style="margin-top: 12px">仅显示在线用户</el-checkbox>
    </div>

    <!-- 统计信息 -->
    <div class="stats-bar">
      <span>共 {{ store.clientUsersTotal }} 个用户</span>
      <span>在线: {{ store.clientUsers.filter(u => u.online_status).length }}</span>
    </div>

    <!-- 用户列表 -->
    <div v-loading="store.clientUsersLoading" class="user-list-container">
      <div v-if="filteredUsers.length === 0" class="empty-state">
        <el-empty description="暂无用户" />
      </div>

      <div v-for="user in filteredUsers" :key="user.id" class="user-item" @click="startChat(user)">
        <div class="user-avatar">
          <el-avatar :size="42" :src="user.avatar">
            {{ user.name.charAt(0) }}
          </el-avatar>
          <span v-if="user.online_status" class="online-badge" />
        </div>

        <div class="user-info">
          <div class="user-name">
            {{ user.name }}
            <el-tag v-if="user.online_status" type="success" size="small">在线</el-tag>
          </div>
          <div class="user-contact">
            <span v-if="user.phone">
              <el-icon><Phone /></el-icon>
              {{ user.phone }}
            </span>
            <span v-if="user.email">
              <el-icon><Message /></el-icon>
              {{ user.email }}
            </span>
          </div>
          <div class="user-meta">
            <span>注册: {{ formatTime(user.registered_at) }}</span>
            <span v-if="user.last_active_at">最后活跃: {{ formatTime(user.last_active_at) }}</span>
          </div>
        </div>

        <div class="user-actions">
          <el-button type="primary" size="small" :icon="'ChatDotRound'">发起聊天</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.user-list-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;

  .panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .close-btn {
      font-size: 20px;
      color: #909399;
      cursor: pointer;

      &:hover {
        color: #303133;
      }
    }
  }

  .search-section {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
  }

  .stats-bar {
    display: flex;
    justify-content: space-between;
    padding: 12px 20px;
    font-size: 13px;
    color: #606266;
    background: #f8f9fb;
  }

  .user-list-container {
    flex: 1;
    padding: 12px 0;
    overflow-y: auto;

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }

    .user-item {
      display: flex;
      gap: 12px;
      align-items: center;
      padding: 12px 20px;
      cursor: pointer;
      border-bottom: 1px solid #f0f0f0;
      transition: all 0.2s;

      &:hover {
        background: #f8f9fb;

        .user-actions {
          opacity: 1;
        }
      }

      .user-avatar {
        position: relative;
        flex-shrink: 0;

        .online-badge {
          position: absolute;
          right: 0;
          bottom: 0;
          width: 12px;
          height: 12px;
          background: #67c23a;
          border: 2px solid #fff;
          border-radius: 50%;
        }
      }

      .user-info {
        flex: 1;
        min-width: 0;

        .user-name {
          display: flex;
          gap: 8px;
          align-items: center;
          margin-bottom: 4px;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
        }

        .user-contact {
          display: flex;
          gap: 16px;
          margin-bottom: 4px;
          font-size: 12px;
          color: #909399;

          span {
            display: flex;
            gap: 4px;
            align-items: center;
          }

          .el-icon {
            font-size: 12px;
          }
        }

        .user-meta {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: #c0c4cc;
        }
      }

      .user-actions {
        opacity: 0;
        transition: opacity 0.2s;
      }
    }
  }
}
</style>
